package mdb

import (
	"fmt"
	"gitee.com/dennis-mxx/mxx-core/mlogger"
	"gitee.com/dennis-mxx/mxx-core/msystem"
	"github.com/jmoiron/sqlx"
	"time"
)

var SqlIte3 *SQLExecute

func InitSqlIte3() {
	if msystem.SqlIte3DataSource.DataSourceAddr == "" {
		return
	}
	if msystem.SqlIte3DataSource.MaxIdleConn == 0 {
		msystem.SqlIte3DataSource.MaxIdleConn = 5
	}
	if msystem.SqlIte3DataSource.MaxOpenConn == 0 {
		msystem.SqlIte3DataSource.MaxOpenConn = 600
	}
	if msystem.SqlIte3DataSource.Timeout == 0 {
		msystem.SqlIte3DataSource.Timeout = 30
	}

	db := ConnectionSqlite3(msystem.SqlIte3DataSource)
	if db != nil {
		SqlIte3 = &SQLExecute{DB: db}
		mlogger.Logger.Info(fmt.Sprintf("connection sqlite3 database [%s] successful ", msystem.SqlIte3DataSource.DataSourceAddr))
	} else {
		mlogger.Logger.Info(fmt.Sprintf("connection sqlite3 database [%s] failure ", msystem.SqlIte3DataSource.DataSourceAddr))
	}
}

func ConnectionSqlite3(dataSource *msystem.SqlIte3Options) *sqlx.DB {
	defer mlogger.FormatException()
	driverName := dataSource.DataSourceAddr

	db := sqlx.MustConnect(`sqlite3`, driverName)
	timeout := time.Duration(dataSource.Timeout)
	db.DB.SetMaxOpenConns(dataSource.MaxOpenConn)        // 用于设置最大打开的连接数，默认值为0表示不限制
	db.DB.SetMaxIdleConns(dataSource.MaxIdleConn)        // 用于设置闲置的连接数
	db.DB.SetConnMaxLifetime(timeout * time.Millisecond) // 设置一个超时时间，时间小于数据库的超时时间即可
	return db
}
